package day04;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(int[] elem) {
        this.elem = new int[10];
    }

    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    /**
     * 创建大根堆
     */
    public void createBigHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, usedSize);
        }
    }

    /**
     * @param parent
     * @param end
     */
    private void siftDown(int parent, int end) {
        int child = 2 * parent + 1;
        //说明有左右孩子
        while (child < end) {
            if (child + 1 < end && elem[child] < elem[child + 1]) {
                child++;
            }
            //走到这里，说明child 一定是左右孩子最大值的下标
            if (elem[child] > elem[parent]) {
                //进行交换
                swap(child, parent);
                //向下调整
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
}
